package com.mall.user.services;

import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.exception.ValidateException;
import com.mall.user.IUserRegisterService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import com.mall.user.dto.UserVerifyRequest;
import com.mall.user.dto.UserVerifyResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class UserRegisterServiceImpl implements IUserRegisterService {
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private UserVerifyMapper userVerifyMapper;
    @Autowired
    private JavaMailSender mailSender;

    @Override
    public UserRegisterResponse userRegister(UserRegisterRequest request) {
        UserRegisterResponse userRegisterResponse = new UserRegisterResponse();
        try {
            // 判空验证
            request.requestCheck();

            // 验证用户名或邮箱是否重复
            validateUsernameOrEmail(request);

            // 向用户表插入一条数据
            Member member = new Member();
            member.setUsername(request.getUserName());
            // 密码加密
            String password = DigestUtils.md5DigestAsHex(request.getUserPwd().getBytes());
            member.setPassword(password);
            member.setEmail(request.getEmail());
            member.setCreated(new Date());
            member.setUpdated(new Date());
            member.setIsVerified("N");
            member.setState(1);
            int affectedRows = memberMapper.insertSelective(member);
            if (affectedRows != 1) {
                userRegisterResponse.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
                userRegisterResponse.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
                return userRegisterResponse;
            }

            // 向用户验证表插入一条记录
            UserVerify userVerify = new UserVerify();
            userVerify.setUsername(request.getUserName());
            String key = request.getUserName() + request.getUserPwd() + UUID.randomUUID().toString();
            String uuid = DigestUtils.md5DigestAsHex(key.getBytes());
            userVerify.setUuid(uuid);
            userVerify.setIsExpire("N");
            userVerify.setIsVerify("N");
            userVerify.setRegisterDate(new Date());
            int rows = userVerifyMapper.insertSelective(userVerify);
            if (rows != 1) {
                userRegisterResponse.setCode(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getCode());
                userRegisterResponse.setMsg(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getMessage());
                return userRegisterResponse;
            }


            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendEmail(uuid, request);
                }
            }).start();

            log.info("用户注册成功，注册参数request:{}", JSON.toJSONString(request));
            userRegisterResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            userRegisterResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        } catch (ValidateException e) {
            userRegisterResponse.setCode(e.getErrorCode());
            userRegisterResponse.setMsg(e.getMessage());
        } catch (Exception e) {
            userRegisterResponse.setCode(SysRetCodeConstants.DB_EXCEPTION.getCode());
            userRegisterResponse.setMsg(SysRetCodeConstants.DB_EXCEPTION.getMessage());
        }

        return userRegisterResponse;
    }

    /**
     * 发送用户激活邮件
     * @param uuid
     * @param request
     */
    private void sendEmail(String uuid, UserRegisterRequest request) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("[csmall] Email地址验证");
        message.setFrom("995872646@qq.com");
        message.setTo(request.getEmail());
        StringBuilder text = new StringBuilder();
        text.append("您只需点击下面的链接即可激活您的帐号：\n" +
                "http://localhost:8080/user/verify?uuid=").append(uuid).append("&username=").append(request.getUserName());
        message.setText(text.toString());

        mailSender.send(message);
    }

    private void validateUsernameOrEmail(UserRegisterRequest request) {
        Example example1 = new Example(Member.class);
        example1.createCriteria().andEqualTo("username", request.getUserName());
        Example example2 = new Example(Member.class);
        example2.createCriteria().andEqualTo("email", request.getEmail());

        List<Member> members = memberMapper.selectByExample(example1);
        if (members.size() != 0)
            throw new ValidateException(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode(), SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());

        List<Member> memberList = memberMapper.selectByExample(example2);
        if (memberList.size() != 0)
            throw new ValidateException(SysRetCodeConstants.EMAIL_ALREADY_EXISTS.getCode(), SysRetCodeConstants.EMAIL_ALREADY_EXISTS.getMessage());
    }
    /**
     * 用户注册激活
     * 2021/8/25
     **/
    @Override
    public void userRegisterActivate(UserVerifyRequest userVerifyRequest) {
        UserVerifyResponse userVerifyResponse = new UserVerifyResponse();
        try{
            //根据username修改tb_member表中的isVerified
            userVerifyRequest.requestCheck();
            Example memberExample = new Example(Member.class);
            Example.Criteria criteria = memberExample.createCriteria();
            criteria.andEqualTo("username",userVerifyRequest.getUserName());
            Member member = new Member();
            member.setIsVerified("Y");
            memberMapper.updateByExampleSelective(member,memberExample);
            //根据uuid修改tb_user_verify表中的is_verified
            Example userExample = new Example(UserVerify.class);
            Example.Criteria criteria1 = userExample.createCriteria();
            criteria1.andEqualTo("uuid",userVerifyRequest.getUuid());
            UserVerify userVerify = new UserVerify();
            userVerify.setIsVerify("Y");
            userVerifyMapper.updateByExampleSelective(userVerify,userExample);
        } catch (ValidateException e) {
            userVerifyResponse.setCode(e.getErrorCode());
            userVerifyResponse.setMsg(e.getMessage());
        }

    }
}
